package com.example.boot.modules.system.controller;

import cn.hutool.core.lang.tree.Tree;
import com.example.boot.modules.system.constant.PM;
import com.example.boot.modules.system.convert.AuthorityConvert;
import com.example.boot.modules.system.dto.AuthorityDto;
import com.example.boot.modules.system.entity.Authority;
import com.example.boot.modules.system.service.IAuthorityService;
import com.example.boot.modules.system.vo.AuthorityVo;
import com.example.starter.security.anntation.AuthUser;
import com.example.starter.security.pojo.ExampleUser;
import com.example.starter.util.Response;
import com.example.starter.webmvc.valid.CreateValid;
import com.example.starter.webmvc.valid.UpdateValid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/system/authority")
@RequiredArgsConstructor
@RestController
public class AuthorityController {

    private final IAuthorityService service;

    @PreAuthorize("hasAuthority('"+ PM.SYS_AUTHORITY_WRITE + "')")
    @PostMapping
    public Response<Boolean> create(@RequestBody @Validated(CreateValid.class) AuthorityDto authorityDto) {
        service.create(authorityDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_AUTHORITY_WRITE + "')")
    @PutMapping
    public Response<Boolean> update(@RequestBody @Validated(UpdateValid.class) AuthorityDto authorityDto) {
        service.update(authorityDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_AUTHORITY_WRITE + "')")
    @DeleteMapping("/{id}")
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        service.deleteById(id);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_AUTHORITY_READ + "')")
    @GetMapping("/{id}")
    public Response<AuthorityVo> findById(@PathVariable("id") Long id) {
        Authority authority = service.getById(id);
        return Response.ok(AuthorityConvert.INSTANCE.toAuthorityVo(authority));
    }

    @GetMapping("/menu")
    public Response<List<Tree<Long>>> listWithTreeMenu(@AuthUser ExampleUser user) {
        return Response.ok(service.listWithTreeMenu(user.getRoles()));
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_AUTHORITY_READ + "')")
    @GetMapping("/tree")
    public Response<List<Tree<Long>>> listWithTree() {
        return Response.ok(service.listWithTree());
    }
}
